package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.enums.SexEnum;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyCenterService {

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @DubboReference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @DubboReference(version = "1.0.0")
    private UserApi userApi;

//    @Autowired
//    private UserInfoService userInfoService;

    @Autowired
    private IMService imService;

    @Autowired
    private TanHuaService tanHuaService;

    @Autowired
    private SettingsService settingsService;

    @DubboReference(version = "1.0.0")
    private QuestionApi questionApi;

    @DubboReference(version = "1.0.0")
    private BlackListApi blackListApi;


    public UserInfoVo queryUserInfoByUserId(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            //如果查询id为null，就表示查询当前用户信息
            userId = UserThreadLocal.get();
        }
        //查询用户信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    public Boolean isLike(Long userId) {
        return this.userLikeApi.isLike(UserThreadLocal.get(), userId);
    }

    public CountsVo queryCounts() {
        Long userId = UserThreadLocal.get();
        CountsVo countsVo = new CountsVo();
        countsVo.setFanCount(this.userLikeApi.queryFanCount(userId));
        countsVo.setLoveCount(this.userLikeApi.queryLikeCount(userId));
        countsVo.setEachLoveCount(this.userLikeApi.queryMutualLikeCount(userId));
        return countsVo;
    }

    //更新用户信息
    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        Long userId = UserThreadLocal.get();

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setNickName(userInfoVo.getNickname());
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setAge(Integer.valueOf(userInfoVo.getAge()));
        userInfo.setSex(StringUtils.equalsIgnoreCase(userInfoVo.getGender(), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIncome(userInfoVo.getIncome());
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setMarriage(userInfoVo.getMarriage() == 1 ? "已婚" : "未婚");

        return this.userInfoApi.updateUserInfoByUserId(userInfo);
    }

    public PageResult queryLikeList(Integer type, Integer page, Integer pageSize, String keyword) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();

        List<Object> userIdList = null;
        //1.互相关注 2.关注 3.粉丝 4.谁看过我
        switch (type) {
            case 1: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryMutualLikeList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            case 2: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryLikeList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "likeUserId");
                break;
            }
            case 3: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryFanList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            case 4: {
                PageInfo<Visitors> pageInfo = this.visitorsApi.visitorsList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "visitorUserId");
                break;
            }
            default:
                return pageResult;
        }
        List<UserInfo> userInfoList;
        //如果搜索框不为空，根据用户名查询
        if (ObjectUtil.isNotEmpty(keyword)) {
            userInfoList = this.userInfoApi.queryLikeNickName(keyword, userIdList);
        } else {
            userInfoList = this.userInfoApi.queryByUserIdList(userIdList);
        }
        ArrayList<UserLikeListVo> userLikeLIstVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UserLikeListVo userLikeListVo = BeanUtil.toBeanIgnoreError(userInfo, UserLikeListVo.class);
            userLikeListVo.setId(userInfo.getUserId());
            userLikeListVo.setAvatar(userInfo.getLogo());
            userLikeListVo.setNickname(userInfo.getNickName());
            userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeListVo.setAge(userInfo.getAge());
            userLikeListVo.setCity(userInfo.getCity());
            userLikeListVo.setEducation(userInfo.getEdu());
            userLikeListVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
            Double score = this.recommendUserApi.queryScore(userId, userInfo.getUserId());
            userLikeListVo.setMatchRate(Convert.toInt(score));
            userLikeListVo.setAlreadyLove(userLikeApi.isLike(userId, userInfo.getUserId()));
            userLikeLIstVos.add(userLikeListVo);
        }
        pageResult.setItems(userLikeLIstVos);
        return pageResult;
    }

    //取消喜欢
    public void disLike(Long userId) {
        Long user = UserThreadLocal.get();
        Boolean result = this.userLikeApi.isLike(user, userId);
        if (result) {
            this.userLikeApi.notLikeUser(user, userId);
            this.imService.removeUser(userId);
        }
    }

    /**
     * 喜欢粉丝
     *
     * @param userId
     */
    public void likeFan(Long userId) {
        this.tanHuaService.likeUser(userId);
    }


    public SettingsVo querySettings() {
        SettingsVo settingsVo = new SettingsVo();
        Long userId = UserThreadLocal.get();

        //设置用户的基本信息
        settingsVo.setId(userId);
        settingsVo.setPhone(this.userApi.queryById(userId).getMobile());

        //查询用户的配置数据
        Settings settings = this.settingsService.querySettings(userId);
        if (ObjectUtil.isNotEmpty(settings)) {
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
        }

        //查询陌生人问题
        settingsVo.setStrangerQuestion(this.tanHuaService.queryQuestion(userId));

        return settingsVo;
    }

    public Object saveQuestions(String content) {
        Long userId = UserThreadLocal.get();
        Boolean result = this.questionApi.saveQuestion(userId, content);
        if (!result) {
            return ErrorResult.builder().errCode("500").errMessage("问题保存失败...").build();
        }
        return null;
    }

    public PageResult queryBlackList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        Integer count = this.blackListApi.queryBlackListCount(userId);
        pageResult.setCounts(count);
        pageResult.setPages(PageUtil.totalPage(count, pageSize));
        PageInfo<BlackList> pageInfo = this.blackListApi.queryBlackList(userId, page, pageSize);
        List<BlackList> records = pageInfo.getRecords();

        ArrayList<BlackListVo> blackListVos = new ArrayList<>();

        for (BlackList record : records) {
            BlackListVo blackListVo = new BlackListVo();
            Long blackUserId = record.getBlackUserId();
            UserInfo userInfo = this.userInfoApi.queryByUserId(blackUserId);
            blackListVo.setId(userInfo.getUserId());
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setNickname(userInfo.getNickName());
            blackListVo.setGender(userInfo.getSex().name().toLowerCase());
            blackListVo.setAge(userInfo.getAge());
            blackListVos.add(blackListVo);
        }

        pageResult.setItems(blackListVos);

        return pageResult;
    }

    public Object deleteBlackUser(Long blackUserId) {
        Long userId = UserThreadLocal.get();
        Boolean result= this.blackListApi.deleteBlackUser(userId,blackUserId);
        if (result){
           return null;
        }
        return ErrorResult.builder().errCode("500").errMessage("移除黑名单失败").build();
    }

    //更新设置
    public Object updateNotifications(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        Long userId = UserThreadLocal.get();
         this.settingsService.updateNotifications(userId,likeNotification,pinglunNotification,gonggaoNotification);
    return null;
    }
}